/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 *
 * @author Johan
 */
public class LoginPanel extends JPanel implements ActionListener{
    private JButton loginButton;
    private JTextField userField;
    private JTextField passwordField;
    private GridBagConstraints c;
    private MainPanel mainPanel;
    public LoginPanel(MainPanel mainPanel){
        this.mainPanel = mainPanel;
        c = new GridBagConstraints();
        setLayout(new GridBagLayout());
        createComponents();
        addComponents();
    }
    private void createComponents(){
        loginButton = new JButton("Login");
        loginButton.addActionListener(this);
        
        userField = new JTextField(9);
        
        passwordField = new JPasswordField(9);
    }
    private void addComponents(){
        
        c.gridx = 0;
        c.gridy = 0;
        add(userField,c);
        c.gridy = 1;
        add(passwordField,c);
        c.gridy = 2;
        add(loginButton,c);
        
    }
    private void validateLogin(String typedPassword, String retrievedPassword){
        if(typedPassword.equals(retrievedPassword)){
            mainPanel.setCurrentUser(userField.getText());
            mainPanel.swapScreen(MainPanel.USERPANEL);
        }
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == loginButton){
            try {
                validateLogin(passwordField.getText(),mainPanel.dbHandler.getPassword(userField.getText()));
            } catch (SQLException ex) {
                Logger.getLogger(LoginPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
}
